package info.hexin.img.font;

import java.awt.Font;
import java.awt.FontFormatException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by infi.he on 2016/2/16.
 */
public class FontManager {
    private static final Map<String, Font> caches = new HashMap<String, Font>();

    static {
        for (FontType fontType : FontType.values()) {
            InputStream fontStream = null;
            try {
                fontStream = FontManager.class.getResourceAsStream(fontType.getPath());
                Font font = Font.createFont(Font.TRUETYPE_FONT, fontStream);
                caches.put(fontType.getName(), font);
            } catch (FontFormatException e) {
                throw new RuntimeException(e);
            } catch (IOException e) {
                throw new RuntimeException(e);
            } finally {
                if (fontStream != null) {
                    try {
                        fontStream.close();
                    } catch (IOException ignore) {

                    }
                }
            }
        }
    }

    public static Font getFont(FontType fontType) {
        return caches.get(fontType.getName());
    }

    public static Font getFont(FontType fontType, int size) {
        String key = fontType.getName() + "_" + size;
        Font font = caches.get(key);
        if (font == null) {
            font = caches.get(fontType.getName());
            font = font.deriveFont(Font.PLAIN, size);
            caches.put(key, font);
        }
        return font;
    }
}
